package com.wjs.gulimall.gulimallware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.rabbitmq.client.Channel;
import com.wjs.gulimall.gulimallware.entity.WareOrderTaskDetailEntity;
import com.wjs.gulimall.gulimallware.entity.WareOrderTaskEntity;
import com.wjs.gulimall.gulimallware.exception.NoStockException;
import com.wjs.gulimall.gulimallware.feign.OrderFeignService;
import com.wjs.gulimall.gulimallware.feign.ProductFeignService;
import com.wjs.gulimall.gulimallware.service.WareOrderTaskDetailService;
import com.wjs.gulimall.gulimallware.service.WareOrderTaskService;
import com.wjs.gulimall.gulimallware.vo.LockStockResult;
import com.wjs.gulimall.gulimallware.vo.OrderItemVo;
import com.wjs.gulimall.gulimallware.vo.OrderVo;
import com.wjs.gulimall.gulimallware.vo.WareSkuLockVo;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.wjs.gulimall.gulimallware.dao.WareSkuDao;
import com.wjs.gulimall.gulimallware.entity.WareSkuEntity;
import com.wjs.gulimall.gulimallware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WareOrderTaskService wareOrderTaskService;

    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    private OrderFeignService orderFeignService;

    private void unLockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        this.baseMapper.unLockStock(skuId, num, wareId);
        //更新工作单的状态
        WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
        detailEntity.setId(taskDetailId);
        detailEntity.setLockStatus(2);//改变状态为已解锁
        wareOrderTaskDetailService.updateById(detailEntity);
    }



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper=new QueryWrapper<>();
        String skuId= (String) params.get("skuId");
        if(!StringUtils.isEmpty(skuId)){
            wrapper.eq("sku_id",skuId);
        }
        String wareId= (String) params.get("wareId");
        if(!StringUtils.isEmpty(wareId)){
            wrapper.eq("ware_id",wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        List<WareSkuEntity> list = this.baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if(list==null||list.size()==0){
            WareSkuEntity wareSkuEntity=new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            wareSkuEntity.setStock(skuNum);
            //远程查询SKU的名字
            try {
                R info = productFeignService.info(skuId);
                if(info.getCode()==0){
                    Map<String,Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
                    wareSkuEntity.setSkuName((String) skuInfo.get("skuName"));
                }
            } catch (Exception e) {
            }
            this.save(wareSkuEntity);
        }else{
            this.baseMapper.addStock(skuId,wareId,skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkusHasstock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map((sku) -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            vo.setSkuId(sku);
            Long count=baseMapper.getSkuSumStock(sku);
            vo.setHasStock(count==null?false:count>0);
            return vo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 为某个订单锁库存
     * @param vo
     * @return
     */
    @Override
    @Transactional
    public Boolean orderLockStocks(WareSkuLockVo vo) {
        WareOrderTaskEntity entity=new WareOrderTaskEntity();
        entity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(entity);

        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> stocks = locks.stream().map(lock -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            skuWareHasStock.setSkuId(lock.getSkuId());
            //查询这个商品在哪里有库存
            List<Long> wareIds = this.baseMapper.listWareIdBySkuId(lock.getSkuId());
            skuWareHasStock.setWareId(wareIds);
            skuWareHasStock.setNum(lock.getCount());
            return skuWareHasStock;
        }).collect(Collectors.toList());
        //锁定库存
        for (SkuWareHasStock stock : stocks) {
            Boolean skuStocked=false;
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareId();
            Integer num = stock.getNum();
            if(wareIds==null||wareIds.size()==0){
                //如果仓库里都没有这个商品，抛异常
                throw new NoStockException(skuId);
            }
            for (Long wareId : wareIds) {
                //成功返回1，否则返回0
                Long count=this.baseMapper.lockSkuStock(skuId,wareId,num);
                if(count==1){
                    //当前仓库锁成功
                    skuStocked=true;
                    //告诉mq锁库存成功
                    WareOrderTaskDetailEntity detailEntity=new WareOrderTaskDetailEntity(null,skuId,"",stock.getNum(),entity.getId(),wareId,1);
                    wareOrderTaskDetailService.save(detailEntity);
                    StockLockedTo lockedTo=new StockLockedTo();
                    lockedTo.setId(entity.getId());
                    StockDetailTo detailTo = new StockDetailTo();
                    BeanUtils.copyProperties(detailEntity,detailTo);
                    //只发id不行，防止回滚后找不到数据
                    lockedTo.setDetail(detailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",lockedTo);
                    break;
                }else {
                    //当前仓库锁失败，重试下一个
                }
            }
            //如果当前sku所有仓库都没有锁住
            if(skuStocked==false){
                throw new NoStockException(skuId);
            }
        }
        //3 能走到这，商品肯定全部锁住

        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {
        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();
        WareOrderTaskDetailEntity detailEntity = wareOrderTaskDetailService.getById(detailId);
        if(detailEntity!=null){
            //解锁
            Long id = to.getId();
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            R r = orderFeignService.getOrderStatus(orderSn);
            if(r.getCode()==0){
                OrderVo data = (OrderVo) r.getData(new TypeReference<OrderVo>() {
                });
                if(data==null||data.getStatus()==4){
                    //如果没有这个订单或者订单被取消，则要进行库存解锁
                    if(detailEntity.getLockStatus()==1){
                        unLockStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum(),detailId);
                    }
                }
            }else {
                //消息拒绝之后重新放入队列
                throw new RuntimeException("远程服务失败\"远程服务失败\"");
            }
        }else {
            //无需解锁
        }
        //1 解锁 先去数据库查询这个订单解库存的消息
        // 有：
        // 没有：锁定库存出现异常导致数据回滚，这种情况无需解锁
    }

    /**
     * 防止订单服务卡断，导致库存一直改不了
     * @param to
     */
    @Override
    @Transactional
    public void unlockStock(OrderTo to) {
        String orderSn = to.getOrderSn();
//        R r = orderFeignService.getOrderStatus(orderSn);
        WareOrderTaskEntity task=wareOrderTaskService.getTaskByOrderSn(orderSn);
        Long taskId = task.getId();
        List<WareOrderTaskDetailEntity> entities = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", taskId)
                .eq("lock_status",1));
        for (WareOrderTaskDetailEntity entity : entities) {
            unLockStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getId());
        }

    }

    @Data
    class SkuWareHasStock{
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }


}